<template>
	<section class="b-title">
		<el-input
			v-model="articleForm.title"
			placeholder="输入文章标题"
			size="large"
		/>
		<el-popover trigger="click" placement="bottom-start" width="600">
			<template #reference>
				<el-button type="primary" size="large">保存</el-button>
			</template>
			<el-form :model="articleForm">
				<el-form-item
					label="分类"
					prop="type"
					:rules="[
						{
							required: true,
							message: '分类不能为空',
							blur: 'change',
						},
					]"
				>
					<el-radio-group v-model="articleForm.type">
						<el-radio
							v-for="item in articleType"
							:key="item.value"
							:label="item.value"
							border
						>
							{{ item.label }}
						</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item
					label="概述"
					prop="desc"
					:rules="[
						{
							required: true,
							message: '概述不能为空',
							trigger: 'blur',
						},
					]"
				>
					<el-input
						v-model="articleForm.desc"
						type="textarea"
						maxlength="200"
					/>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="submit">保存</el-button>
				</el-form-item>
			</el-form>
		</el-popover>
		<el-button type="danger" size="large" @click="() => router.go(-1)">
			退出
		</el-button>
	</section>
	<mavon-editor
		ref="md"
		v-model="articleForm.content"
		:box-shadow="false"
		:ishljs="true"
		:external-link="externalLink"
		:toolbars="toolbars"
		@img-add="addImage"
	/>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { articleType, toolbars, externalLink } from '@/const/blog.js'
import {
	updateArticleApi,
	uploadApi,
	createArticleApi,
	getArticleByIdApi,
} from '@/api/api.js'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const articleForm = reactive({
	content: '',
	title: '',
	type: '0',
	desc: '',
})

onMounted(async () => {
	if (route.query.id) {
		let res = await getArticleByIdApi(Number(route.query.id))
		Object.assign(articleForm, res.data)
	}
})

const md = ref(null)

const addImage = async (pos, file) => {
	let res = await uploadApi({ file: file })
	md.value.$img2Url(pos, import.meta.env.VITE_APP_IP + res.file.url)
}

const submit = async () => {
	try {
		if (route.query.id) {
			await updateArticleApi(articleForm)
		} else {
			await createArticleApi(articleForm)
		}
		ElMessage.success('操作成功')
		router.go(-1)
	} catch (err) {
		console.log(err)
	}
}
</script>

<style scoped>
.b-title {
	display: flex;
	justify-content: space-between;
	align-items: center;
}
</style>
